package com.newcapec.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:处理跨域的过滤器
 * @Author:yangshupeng
 * @Date: 2022/4/5 0:27
 * @Version:1.0
 */
@WebFilter("/*")
public class CrossFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //Access-Control-Allow-Origin:可以跨域请求的资源地址
        response.setHeader("Access-Control-Allow-Origin", "*");
        //Access-Control-Allow-Methods:可以跨域请求的方式
        response.setHeader("Access-Control-Allow-Methods", "*");
        //Access-Control-Max-Age:配置跨域请求时预判请求的间隔请求时间
        //0表示不间隔，3600每个小时预判一次
        response.setHeader("Access-Control-Max-Age", "3600");
        //Access-Control-Allow-Headers响应头包含的内容
        //x-requested-with异步
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        //Access-Control-Allow-Credentials凭证
        response.setHeader("Access-Control-Allow-Credentials", "true");

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
